<?php

/**
 * Filename: database.class.php
 * Description: Holds all of the database connection and generic query functions
 * Version: 1.0
 * Copyright: Andrew Lowther
 * Author: Andrew Lowther
 *
 * Usage: When creating functions, declare a global $db variable then just use $db->functionName to use the functions in this class
 */
 
// Define variables to be passed into the function to return values
 
/**
 * @var: Object
 * @desc: Return an object from the database, this is the default return
 */
define('OBJECT', 'OBJECT', true);
 
/**
 * @var: Array_A
 * @desc: Return an associative/numerically indexed array
 */
define('ARRAY_A', 'ARRAY_A', false);
 
class Db_Database {
 
	/**
	 * @var: $host, $user, $pass, $dbase
	 * @type: Private: String
	 *
	 * @usage: To contain all the database connection string
	 */
    private $host, $user, $pass, $dbase;
	
	/**
	 * @var: $result, $returnarr, $obj
	 * @type: Public: MySql Object | Array | Object
	 *
	 * @usage: Contain the MySql results, arrays and objects
	 */
    public $result, $returnarr, $obj;
    
    /**
     * @var: lastquery
     * @type: string
     *
     * @usage: Debugging purposes, holds the last query run
     */
    var $lastquery = "";
    
    /**
     * @var: publictables
     * @type: array
     *
     * @usage: Contain the array of the current tables
     */
    var $publictables = array();

    // Create a constructor function to connect
    public function __construct() {
   
        // Register the __destruct function so that the class returns true at the end
        register_shutdown_function(array(&$this, "__destruct"));
       
        // Set up the public variables with the data we need
        $this->host = DB_HOST;
        $this->user = DB_USER;
        $this->pass = DB_PASSWORD;
        $this->dbase = DB_DATABASE;
       
        // Instantiate a connection
        $this->connectToDb();
        
        // Set up the public tables variable, only run it if the variable is empty to make sure we're not calling every time
        if (empty($this->publictables)) {
        
        	$this->publictables = $this->getAllTables();
        	
        }
   
    }
   
    // Generic query function
    public function setQuery($query = null, $true = false) {

		if ($query) {
		
			// Create an sql variable that contains the query string
			$sql = $query;
		   
			// Get the result
			$this->result = mysql_query($sql) or die (mysql_error());
		   
			// If the true variable is true, then return true rather than the result
			if ($true == true) {
		   
				// If this succeeded then we return the true
				if ($this->result) {
			   
			   		$lastquery = $query;
			   
					return true;
			   
				} else {
				
					$lastquery = $query;
			   
					return false;
			   
				}
		   
			} else {
		   
		   		$lastquery = $query;
		   
				// Return the result
				return $this->result;
			   
			}
			
		}
   
    }
   
    // Function to use the query function and return whatever format the user requests
    public function getQuery($query = null, $output = OBJECT) {
   
        // If the query isn't null then perform a query
        if ($query) {
       
            // Create a query using the $query variable
            $sql = $query;
            $result = $this->setQuery($sql) or die (mysql_error());
           
            // Get the query and return the object
            if ($output == OBJECT) {
				
				// Set a num rows counter to 0 to set up an integer reliant object
				$num_rows = 0;
				
				// Loop through the object to get the data
				while ($row = mysql_fetch_object($result)) {
				
					$this->obj[$num_rows] = $row;
					$num_rows++;
					
				}
				
				// Free the result
				mysql_free_result($result);
				
				// Return the numerically indexed object
                return $this->obj;
           
            } else if ($output == ARRAY_A) {
               
                // Create an empty array to hold our data
                $this->returnarr = array();
           
                while ($return = mysql_fetch_array($result)) {
               
                    // Push all the data into the array
                    array_push($this->returnarr, $return);
               
                }
                
                // Free the result
				mysql_free_result($result);
               
                // Return the array
                return $this->returnarr;
           
            }
       
        }
   
    }
   
    // Function to insert data into the given table
    public function insertRow($table, $insert) {
   
        // Create an empty sql variable
        $sql = "";
       
        // Add the insert into statement
        $sql .= "INSERT INTO `".$table."` VALUES (NULL, ";
       
        // Run through the insert array to build the sql
        foreach($insert as $data) {
       
            $sql .= "'".$data."', ";
       
        }
       
        // Remove the last comma
        $sql = substr_replace($sql, "", -2);
       
        // Append the close bracket
        $sql .= ")";
       
        // Run the query and make sure it return true
        if ($this->setQuery($sql, true)) {
           
            return true;
           
        } else {
       
            echo "An error occurred and your data was not written to the database";
            return false;
       
        }
   
    }
   
    // Function to update rows
    public function updateRow($table, $data, $where, $id) {
   
        // Create an empty sql variable
        $sql = "";
       
        // Append the sql statement with the table
        $sql .= "UPDATE `".$table."` SET ";
       
        // Run through the data array to append the required data
        foreach($data as $col => $update) {
       
            $sql .= $col." = '".$update."', ";
       
        }
       
        // Remove the last comma
        $sql = substr_replace($sql, "", -2);
       
        // Append the $id with a WHERE statement
        $sql .= " WHERE `".$where."` = '".$id."'";
       
        // Run the query and return either true or false depending on success
        if ($this->setQuery($sql, true)) {
       
            return true;
       
        } else {
       
            echo "An error occurred and your data was not written to the database";
            return false;
       
        }
   
    }
   
    // Function to return aa count of a particular table
    public function countThis($query) {
       
        // Run the query and return a count
        $result = $this->setQuery($query);
       
        // Set up the count
        $count = mysql_num_rows($result);
       
        // Return the number of rows
        return $count;
   
    }
    
    // Function to get all the current tables
    public function getAllTables() {
    
    	return $this->getQuery("SHOW TABLES FROM `".$this->dbase."`", ARRAY_A);
    
    }
    
    // Function to flush all data
    public function flushThis() {
    
    	$result = "";
    	$obj = "";
    	$lastquery = "";
    	$publibtables = array();
    	$returnarr = array();
    
    }
   
    // Destruct function
    public function __destruct() {
 
        return true;
   
    }
   
    // Function to connect using the constructor
    private function connectToDb() {
   
        $connect = mysql_connect($this->host, $this->user, $this->pass);
       
        if ($connect) {
       
            mysql_select_db($this->dbase) or die (mysql_error());
       
        } else {
       
            return "Failure to connect to database";
       
        }
   
    }
 
}
 
?>